
import { reqlogin, GetUserInfo, getBaseInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
const state = {
  token: getToken() || '',
  userInfo: {}
}

const mutations = {
  setToken(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  changeUserinfo(state, info) {
    state.userInfo = info
  },
  removeUser(state) {
    state.userInfo = {}
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  }

}

const actions = {
  async login(context, data) {
    const res = await reqlogin(data)
    context.commit('setToken', res.data)
    // console.log(res)
    // return res
  },
  async getInfo(context) {
    const res1 = await GetUserInfo()
    const res2 = await getBaseInfo(res1.data.userId)
    const res = { ...res1.data, ...res2.data }
    context.commit('changeUserinfo', res)
    return res
  },
  logout(context) {
    context.commit('removeUser')
    context.commit('removeToken')
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

